<?php

use GuzzleHttp\Client;
use Illuminate\Support\Facades\Redis;
use App\Models\Clue;
use Spatie\Permission\Models\Role;
use App\User;

/**
 * @param \Spatie\Permission\Models\Permission::query $query
 * @param array $arr
 * @return mixed
 */
function arrInPermission($query, $arr)
{
    return $query->whereIn('name', $arr)->get();
}

function signature($key, $string)
{
    return base64_encode(hash_hmac('sha256', $string, $key));
}

function crmPullClues($account, $start_time, $end_time, $page = 1, $pageSize = 10)
{
    $payload   = [
        'start_time' => $start_time,
        'end_time'   => $end_time,
        'page'       => $page,
        'page_size'  => $pageSize
    ];
    $timestamp = time();

    $domain = 'https://crm.bytedance.com';
    $url    = '/crm/v2/openapi/pull-clues/';

    $stirng  = "$url?start_time=$start_time&end_time=$end_time $timestamp";
    $sign    = signature($account->key, $stirng);
    $headers = [
        'Signature'    => $sign,
        'Timestamp'    => $timestamp,
        'Access-Token' => $account->token,
        'Content-Type' => 'application/json'
    ];

    $client   = new Client();
    $response = $client->request('GET', $domain . $url, [
        'headers' => $headers,
        'query'   => $payload
    ]);

    return json_decode($response->getBody()->getContents(), true);
}


function saveClue($data, $account_id, $type, $pass = false)
{
    $data = collect($data);
    $name = "clue:$account_id:";

    $data->each(function ($item) use ($name, $account_id, $type, $pass) {
        $date = \Carbon\Carbon::createFromTimestamp($item['create_time'])->toDateString();
        if ($pass || !Redis::hexists($name . $date, $item['clue_id'])) {
            $item['account_id']  = $account_id;
            $item['type']        = $type;
            $item['create_time'] = Carbon\Carbon::createFromTimestamp($item['create_time'])->toDateTimeString();

            Clue::updateOrCreate([
                'clue_id'    => $item['clue_id'],
                'account_id' => $account_id
            ], $item);
            Redis::hset($name . $date, $item['clue_id'], true);
        }
    });
}

function getUserForStatus($status, $type = '')
{
    if ($type) {
        $users = User::role("user:$type");
    } else {
        $users = User::query();
    }

    return $users->select('id')->where('status', $status)->get()->pluck('id');
}

function getOnlineUser($type)
{
    $online = Redis::get("$type:online");
    return $online ? json_decode($online, true) : [];
}

function setOnlineUser($type , $data)
{
    Redis::set("$type:online" , json_encode($data));
}

function distributionClue($clue)
{


}
